package com.zdb.demo.java.leetcode.q2addtwonumbers.demo2;

public class Solution {

    public static void main(String[] args) {
//        [2,4,3]
//        [5,6,4]

        ListNode
                l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode
                l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        
        Solution
                solution = new Solution();
        ListNode resultNode = solution.addTwoNumbers(l1, l2);
        System.out.println(resultNode);

    }

    /**
     * 采用 不同位数相加，大于10给后面一位增加一个进位
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(
            ListNode l1, ListNode l2) {

        int carry = 0;

        ListNode q = l1, p= l2, resultNode = null, currNode, beforeNode = null;
        int currResult;

        while(q != null && p != null) {
            int qi = q == null ? 0 : q.val;
            int pi = p == null ? 0 : p.val;
            currResult = qi + pi + carry;
            carry = currResult / 10;
            currNode = new ListNode(currResult % 10);
            if(resultNode == null) {
                resultNode = currNode;
            } else {
                beforeNode.next = currNode;

            }
            beforeNode = currNode;
            q = q == null ? null : q.next;
            p = p == null ? null : p.next;
        }

        return resultNode;

    }
}

class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }

    @Override public String toString() {
        StringBuffer sb = new StringBuffer();
        ListNode tmp = this;
        while (tmp != null) {
            sb.append(tmp.val).append("->");
            tmp = tmp.next;
        }
        return sb.toString();
    }
}
